define(["utils", "photoswipe"], function (utils, photoswipe) {

    function RowUpDateUtils(config) {
        this.rowInstance = config.rowInstance;
        this.rowData = this.rowInstance.datasource;
        this.pageview = config.pageview;
        this.root = config.root;
    }

    RowUpDateUtils.prototype = {
        refresh: function () {
            var _this = this;
            this.pageview.ajax({
                type: "GET",
                url: "/diaryQuery/getDiaryById/" + this.rowData.id,
                data: {},
                success: function (data) {
                    if (data.code === 0) {
                        data.data.fileStr = data.data.files;  //解决返回数据中缺少fileStr字段而引起的bug(跳到编辑页时无法展示已上传文件)
                        _this.rowInstance.rebind(_this.root._processRowData(data.data));
                    }
                },
                error: function (e) {

                }
            });
        }
    };

    function pageLogic(config) {
        this.pageview = config.pageview;
        this.fullPageKey = this.pageview.config.fullPageKey;

        var _this = this;

        $(document.body).bind("click", function () {
            _this.pageview.refs.time_dropdown_wrap.addClass("displaynone");
        });


    }

    pageLogic.prototype = {
        mainvlayout_didmount:function(sender,params){
            if(this.fullPageKey!=="commonpage_team"){
                sender.components[0].$el.css({display:"none"});
            }else{
                //
            }
        },
        loadDataWhenInTeamPage:function(id){
            this.table.setAjaxConfigParams({groupId: id});
            this.table.loadFirstPageData();
        },
        leftrepeat_itemclick:function(sender,params){
            sender.select();
            this.loadDataWhenInTeamPage(sender.datasource.groupId);
        },
        condition_group_name_init:function(sender,params){
            sender.config.text = sender.datasource.groupName;
        },
        condition_group_count_init:function(sender,params){
            sender.config.text = "("+sender.datasource.groupMemberCount+"人)";
        },
        leftrepeat_didmount:function(sender,params){
            var _this = this;
            if(this.fullPageKey==="commonpage_team"){
                this.pageview.showLoading({
                  text:"正在努力加载...",
                  loadingColor:"#000"
                });
                this.pageview.ajax({
                    type: "GET",
                    timeout:100000000,
                    url: "diaryQuery/getGeneralGroupDiary",
                    data: {},
                    success: function (data) {
                        if (data.code === 0) {
                            sender.bindData(data.data);
                            if(data.data.length>0){
                                sender.components[0].select();
                                _this.loadDataWhenInTeamPage(data.data[0].groupId);
                            }
                        }else{
                            sender.bindData([]);
                        }
                        _this.pageview.hideLoading(data.code === 0);
                    },
                    error: function (e) {
                        sender.bindData([]);
                        _this.pageview.hideLoading(false);
                    }
                });
            }
        },

        image_repeat_click: function (sender, params) {
            var imgsList = sender.parent.parent.datasource,
                imgsProcessList = [];
            imgsList.forEach(function (value, key) {
                imgsProcessList.push({
                    src: value.fileKey,
                    el: sender.$el[0]
                });
            });
            photoswipe.showPhotoWall(imgsProcessList, sender.parent.$el.index());
        },

        time_condition_start_change: function (sender, params) {
            var endDate = this.time_condition_end.getValue();
            if (endDate.date === undefined) {
                this.time_condition_end.setValue(params.date);
            } else {
                if (utils.compareDate(params.date, endDate.date) === 1) {
                    this.time_condition_end.setValue(params.date);
                }
            }
        },
        time_condition_end_init: function (sender) {
            this.time_condition_end = sender;
        },
        time_condition_start_init: function (sender) {
            this.time_condition_start = sender;
        },
        time_condition_end_change: function (sender, params) {
            var startDate = this.time_condition_start.getValue();
            if (startDate.date === undefined) {
                this.time_condition_start.setValue(params.date);
            } else {
                if (utils.compareDate(params.date, startDate.date) === -1) {
                    this.time_condition_start.setValue(params.date);
                }
            }
        },
        main_header_init: function (sender) {
            if (this.fullPageKey === "commonpage_team") {
                sender.config.root = [ "temp_dropdown_btn", "time_dropdown_btn", "create_btn"];
            }
        },
        time_dropdown_wrap_click: function (sender, params) {
            params.e.preventDefault();
            params.e.stopPropagation();
        },
        time_dropdown_btn_click: function (sender, params) {
            params.e.stopPropagation();
            params.e.preventDefault();
            this.pageview.refs.time_dropdown_wrap.removeClass("displaynone");
            //time_dropdown_wrap
        },
        position_init: function (sender) {
            var location = sender.datasource.location || "";
            if (location.length === 0) {
                sender.config.style.display = "none";
            }
        },
        atPersons_init: function (sender) {
            var length = sender.datasource.at.length;

            var atArr = [],atStr;

            if (length === 0) {
                sender.config.style.display = "none";
            }else{
                for(var i = 0 ; i<length ; i++){
                    atArr.push("@"+sender.datasource.at[i].replayUserName);
                }
                atStr = atArr.join('，');

                sender.config.text = atStr;

            }
            sender.datasource.atStr = atStr;
        },
        time_dropdown_clearbtn_click: function () {
            this.pageview.refs.time_dropdown_icon.setText("日期");
            this.pageview.refs.time_dropdown_wrap.addClass("displaynone");
            this.table.deleteAjaxConfigParams({
                beginDate: null,
                endDate: null
            });
            this.table.loadFirstPageData();
        },
        time_dropdown_okbtn_click: function (sender, params) {
            var startTime = this.pageview.refs.time_condition_start.getValue().str;
            var endTime = this.pageview.refs.time_condition_end.getValue().str;

            this.table.setAjaxConfigParams({
                beginDate: startTime,
                endDate: endTime
            });
            this.table.loadFirstPageData();
            this.pageview.refs.time_dropdown_icon.setText(startTime + "至" + endTime);
            this.pageview.refs.time_dropdown_wrap.addClass("displaynone");
        },
        check_goDetail:function(id,params){
            var _this = this;

            this.ModifyRowDict = this.ModifyRowDict || {};
            this.pageview.ajax({
                url: '/diary/detail/' + id,
                type: 'GET',
                success: function(data) {
                    if(data.code === 0) {
                        if(!data.data){
                            //data.data === null时说明这条日志已被删除
                            _this.pageview.showTip({text:"该日志已被删除",duration:1000});
                        }else{
                            //该日志存在,可跳转详情
                            if(_this.fullPageKey==="commonpage_draft"){
                                params.rowInstance.datasource.dataType = data.data.dataType;
                                _this.pageview.showPage({
                                    pageKey: "add",
                                    mode: "slide",
                                    params: {data: params.rowInstance.datasource}
                                });
                            }else{
                                _this.pageview.showPage({
                                    pageKey: "detailpage",
                                    mode: "slide",
                                    params: params
                                });

                            }

                        }
                    }
                    // _this.pageview.hideSubmiting(data.code === 0);
                },
                error: function() {
                    // _this.pageview.hideSubmiting(false);
                }
            });
        },
        table_rowclick: function (sender, params) {
            this.ModifyRowDict = this.ModifyRowDict || {};
            var id = sender.datasource.id.toString();
            var data = {rowInstance: sender};
            this.ModifyRowDict[id] = new RowUpDateUtils({rowInstance: sender, pageview: this.pageview, root: this});
            this.check_goDetail(id,data);
        },
        reply_click:function (sender, params){
            this.ModifyRowDict = this.ModifyRowDict || {};
            var id = sender.datasource.id.toString();
            var data = {rowInstance: sender.rowInstance,type:1};
            this.ModifyRowDict[id] = new RowUpDateUtils({rowInstance: sender.rowInstance, pageview: this.pageview, root: this});
            this.check_goDetail(id,data);
        },
        collect_click: function(sender, params) {
            var _this = this;
            var icon_sender = sender.components.collect_icon;
            var url = '/favorite/add/';

            if(icon_sender.isSelected) {
              // 取消收藏
            url = '/favorite/delete/';
            } else {
                  // 收藏
            }

              this.pageview.ajax({
                  url: url,
                  type: 'POST',
              data:{diaryId:sender.datasource.id},
                  success: function(data) {
                      if(data.code === 0) {
                          if(icon_sender.isSelected){
                              //取消收藏
                              icon_sender.isSelected = false;
                              icon_sender.unSelected();
                              sender.datasource.favorite.isFavorite = 0;
                              sender.datasource.favorite.favoriteNum --;
                          }
                          else {
                              //收藏
                              icon_sender.isSelected = true;
                              icon_sender.selected();
                              sender.datasource.favorite.isFavorite = 1;
                              sender.datasource.favorite.favoriteNum ++;
                          }

                      }
                      // _this.pageview.hideSubmiting(data.code === 0);
                  },
                  error: function() {
                      // _this.pageview.hideSubmiting(false);
                  }
              });
        },

        like_text_click:function (sender, params){
            this.ModifyRowDict = this.ModifyRowDict || {};
            var id = sender.datasource.id.toString();
            var data = {rowInstance: sender.rowInstance,type:2};
            this.ModifyRowDict[id] = new RowUpDateUtils({rowInstance: sender.rowInstance, pageview: this.pageview, root: this});
            this.check_goDetail(id,data);
        },
        delete_icon_init:function(sender){
            if(this.fullPageKey!=="commonpage_draft"){
                sender.config.style.display = "none";
            }
        },
        delete_icon_click:function(sender,params){
            this.selectedRow = sender.rowInstance;
            this.pageview.showDialog("del_dialog");
        },
        del_dialog_cancelbtn_click:function(){
            this.pageview.hideDialog("del_dialog");
        },
        del_dialog_okbtn_click:function(sender){
          this.pageview.hideDialog("del_dialog");
          var _this = this;
          this.pageview.showSubmiting({
              text:"正在处理中...",
              successText:null
          });

          this.pageview.ajax({
              url: '/diary/' + this.selectedRow.datasource.id,
              type: 'DELETE',
              success: function(data) {
                  if(data.code === 0) {
                      _this.pageview.showTip({
                          text: '删除成功',
                          duration: 1000
                      });

                      _this.selectedRow.remove();
                  }
                  _this.pageview.hideSubmiting(data.code === 0);
              },
              error: function() {
                  _this.pageview.hideSubmiting(false);
              }
          });
        },
        like_icon_click:function(sender, params){
            //点击图标的时候直接点赞
            var _this = this;
            this.pageview.ajax({
                url: '/diaryLike/' + sender.datasource.id,
                type: 'POST',
                success: function(data) {
                    if(data.code === 0) {
                        if(sender.isSelected){
                            //取消点赞
                            sender.datasource.isLike = 0;
                            sender.datasource.like.likeNum --;
                            sender.datasource.like.isLike = 0;
                            sender.unSelected();
                        }
                        else {
                            //点赞
                            sender.datasource.isLike = 1;
                            sender.datasource.like.isLike = 1;
                            sender.datasource.like.likeNum ++;
                            sender.selected();
                        }

                        sender.rowInstance.refs.like_text.setText(sender.datasource.like.likeNum +"个赞");
                    }
                    // _this.pageview.hideSubmiting(data.code === 0);
                },
                error: function() {
                    // _this.pageview.hideSubmiting(false);
                }
            });
        },
        reply_text_init:function(sender, params){
            var num = sender.datasource.commentNum;
            sender.config.text = num + "个回复";
        },
        like_text_init:function(sender, params){
            var num = sender.datasource.like.likeNum;
            sender.config.text = num + "个赞";
        },
        like_icon_init:function(sender,params){
            if(sender.datasource.like.isLike===1){
                sender.selected();
                // sender.config.style.color = "#FF6666";
                // sender.config.style.font = "icomoon_e925";
            }else{
                sender.unSelected();
            }
        },
		collect_icon_init: function(sender, params) {

            if(sender.datasource.favorite.isFavorite) {
                sender.selected();
                sender.isSelected = true;
            } else {
                sender.unSelected();
                sender.isSelected = false;
            }
		},
        team_dropdown_btn_click: function (sender, params) {
            this.pageview.refs.time_dropdown_wrap.addClass("displaynone");
            this.pageview.refs.team_dropdown.$el.click();
        },

        depart_dropdown_btn_click:function(){
            this.pageview.refs.time_dropdown_wrap.addClass("displaynone");
            this.pageview.refs.depart_dropdown.$el.click();
        },

        depart_dropdown_btn_init:function(sender,params){
            if(this.fullPageKey!=="commonpage_depart"){
                sender.config.style.display="none";
            }
        },

        depart_dropdown_getdata:function(sender,params){
            this.pageview.ajax({
                type: "GET",
                url: "/team/getCurrentSubDepts",
                data: {},
                success: function (data) {
                    if (data.code === 0) {

                        var re = [{
                            gid: null,
                            deptId: null,
                            deptName: "全部部门"
                        }].concat(data.data);

                        params.success(re);
                    } else {
                        params.error();
                    }
                },
                error: function (e) {
                    params.error();
                }
            });
        },

        team_dropdown_getdata: function (sender, params) {

            this.pageview.ajax({
                type: "GET",
                url: "/group/me",
                data: {},
                success: function (data) {
                    if (data.code === 0) {

                        var re = [{
                            gid: null,
                            id: null,
                            groupName: "全部团队"
                        }].concat(data.data);

                        params.success(re);
                    } else {
                        params.error();
                    }
                },
                error: function (e) {
                    params.error();
                }
            });

        },


        onPageResume: function () {
            var obj;
            if (this.reloadType === "savedraft") {
                this.reloadType = "";
                // alert("reload savedraft");
            } else if (this.reloadType === "modify") {

                obj = this.ModifyRowDict[this.reloadId.toString()];
                if (obj) {
                    obj.refresh();
                }
                this.reloadId = "";
                this.reloadType = "";
                // alert("reload save");
            } else if (this.reloadType === "new") {
                if (this.newRowData) {
                    this.pageview.refs.table.insertRow(this._processRowData(this.newRowData), 0);
                    this.newRowData = null;
                }
            } else if(this.reloadType === "draftSend"){
                 obj = this.ModifyRowDict[this.reloadId.toString()];
                if (obj) {
                    obj.rowInstance.remove();
                }
                this.reloadId = "";
                this.reloadType = "";
            } else {
                // alert("noload");
            }
        },

        temp_dropdown_btn_click: function (sender) {
            this.pageview.refs.time_dropdown_wrap.addClass("displaynone");
            this.pageview.refs.temp_dropdown.$el.click();
        },


        temp_dropdown_getdata: function (sender, params) {

            this.pageview.ajax({
                type: "GET",
                url: "/template/list",
                data: {
                    pageNumber: 1,
                    pageSize: 1000,
                    client: "app"
                },
                success: function (data) {
                    if (data.code === 0) {
                        var dataArr = [{id: 0, title: "全部模版"}].concat(data.data);
                        params.success(dataArr);
                    } else {
                        params.error();
                    }
                }, error: function () {
                    params.error();
                }
            });
        },
        rangeParamsDict: {
            "commonpage_all": 0,
            "commonpage_my": -1,
            "commonpage_atme": 4,
            "commonpage_depart": 1,
            "commonpage_team": 3,
			"commonpage_collect": 0
        },
        table_init: function (sender) {
            this.table = sender;
            var dataStatus = 1;
            if(this.fullPageKey == "commonpage_collect"){
                sender.config.ajaxConfig.url = "/favorite/getMyFavorite";
            }else{
                if (this.fullPageKey == "commonpage_draft") {
                    dataStatus = 0;
                }
                sender.setAjaxConfigParams({range: this.rangeParamsDict[this.fullPageKey] || 0,dataStatus: dataStatus});
            }
        },

        table_didmount: function (sender) {
            if (this.fullPageKey == "commonpage_team") {
                return;
            }
            this.pageview.pageManager.bindOnce("userloaded", function () {
                sender.loadFirstPageData();
            });

        },
        team_dropdown_change: function (sender, params) {
            this.table.setAjaxConfigParams({groupId: params.valData.id});
            this.pageview.refs.team_dropdown_icon.setText(params.valData.groupName);
            this.table.loadFirstPageData();
        },
        depart_dropdown_change:function(sender,params){
            this.table.setAjaxConfigParams({deptId: params.valData.deptId});
            this.pageview.refs.depart_dropdown_icon.setText(params.valData.deptName);
            this.table.loadFirstPageData();
        },
        temp_dropdown_change: function (sender, params) {

            if (params.valData.id === 0) {
                this.table.deleteAjaxConfigParams({templateId: null});
            } else {
                this.table.setAjaxConfigParams({templateId: params.valData.id});

            }
            this.pageview.refs.temp_dropdown_icon.setText(params.valData.title);
            this.table.loadFirstPageData();
        },
        main_body_inner_loadmore: function () {
            this.pageview.refs.table.loadNextPageData();
        },

        main_body_inner_reload: function () {
            this.pageview.refs.table.reload();
        },

        range_icon_init: function (sender) {
            var userid = sender.datasource.user_id;
            var isMY = this.pageview.pageManager.userInfo.id === userid;
            if (sender.datasource.visibleRange === 1 && isMY && sender.datasource.range.length > 0) {

            } else {
                sender.config.style.display = "none";
            }
        },
        files_iteminit: function (sender, params) {
            sender.$el.attr('gotourl', sender.datasource.fileKey);
        },
        file_download_click: function (sender) {
            window.open(sender.datasource.fileKey);
        },
        avatar_init: function (sender) {
            if (sender.config.src === "./imgs/header.png") {
                sender.config.src="";
            } else {
                sender.config.defaultSrc = sender.config.src;
                sender.config.src = sender.config.src + ".thumb.jpg";
            }
        },


        _processRowData: function (rowData) {
            // rowData.content[0]="'";
            // rowData.content[rowData.content.length-1]="'";
            //rowData.content = rowData.content.replace(/<[^,]*?>/g, '').replace(/\\t/g, '  ').replace(/\\n/g,'<br>').replace(/\\/g,'');
            //console.log(rowData.content);
            rowData.content = JSON.parse(rowData.content);
            var files = rowData.fileStr || rowData.files || rowData.diaryFiles || [];
            if (rowData.like) {
                rowData.isLike = rowData.like.isLike;

            } else {
                rowData.isLike = rowData.isLike;
            }
            rowData.range = rowData.range || rowData.diaryVisibleRanges;
            rowData.user_id = rowData.user_id || rowData.userId;

            rowData.images = [];
            rowData.files = [];
            rowData.avatar = rowData.avatar ? rowData.avatar : "./imgs/header.png";

            for (var k = 0; k < files.length; k++) {
                files[k].fileExtension = files[k].fileExtension.toLowerCase();
                if (files[k].fileExtension === '.pic' || files[k].fileExtension === '.jpg' || files[k].fileExtension === '.png' || files[k].fileExtension === '.gif' || files[k].fileExtension === '.bmp' || files[k].fileExtension === '.jpeg') {
                    rowData.images.push(files[k]);
                } else {
                    try{
                        //rowData.fileStr[k].iconPath = this.getFileTypePath(files[k]);
                        files[k].iconPath =  this.getFileTypePath(files[k]);
                    }catch(e){
                        console.log(e);
                    }

                    rowData.files.push(files[k]);
                }
            }
            var time = rowData.diaryTime||rowData.createTime;
            time = utils.ConvertDateToStr(time);
            rowData.content= [{content:time,title:"日志日期",type:"InputText",value:time}].concat(rowData.content);

            return rowData;
        },
        Arr: ["其他", "日报", "周报", "月报", "其他"],
        label_text_right_init: function (sender, params) {
            var diaryType = sender.datasource.diaryType;
            sender.config.text = this.Arr[diaryType] || "其他";
        },

        table_parsedata: function (sender, params) {
            var data = params.data.data;
            if (params.data.code === 0) {
                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        data[i] = this._processRowData(data[i]);
                    }
                }

                return {data: data || [], sumCount: data.pageTotal || 0};
            } else {
                return false;
            }
        },
        getFileTypePath: function (file) {
            var path = "";
            var type = "";
            if (typeof file === "string") {
                type = file;
            } else {
                if (file.fileExtension && file.fileExtension.indexOf(".") === 0) {
                    file.fileExtension = file.fileExtension.substring(1);
                }
                type = file.fileExtension;
            }
            if (type) {
                type = type.toLowerCase();
            }
            switch (type) {
                case "zip":
                case "rar":
                case "tar":
                    path = "./imgs/zip_file.png";
                    break;
                case "txt":
                    path = "./imgs/txt_file.png";
                    break;
                case "png":
                case "jpeg":
                case "jpg":
                case "gif":
                    path = "./imgs/image_file.png";
                    break;
                case "xls":
                case "xlsx":
                    path = "./imgs/excel.png";
                    break;
                case "doc":
                case "docx":
                    path = "./imgs/word_file.png";
                    break;
                case "ppt":
                case "pptx":
                    path = "./imgs/ppt_file.png";
                    break;
                case "pdf":
                    path = "./imgs/pdf_file.png";
                    break;
                case "mp4":
                case "avi":
                case "flv":
                    path = "./imgs/video.png";
                    break;
                default:
                    path = "./imgs/file.png";
                    break;
            }
            return path;
        },
        operation_group_didmount:function(sender){
            if(this.fullPageKey==="commonpage_draft"){
                sender.$el.css({"display":"none"});
            }
        },
        create_btn_click: function (sender) {
            this.pageview.showPage({
                pageKey: "add",
                mode: "slide",
                params:{
                    fullPageKey:this.fullPageKey
                }
            });
        },
        when_init: function (sender, params) {
            sender.config.text = utils.timestampToTimeStr(sender.config.text);
        },
       DateDiff:function(sDate1){
             oDate1  =  new  Date(sDate1);
             oDate2  =  new  Date();
             iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24);
             return  iDays;
         } ,
        group_row_updatetime_init: function (sender, params) {
            var diffDay  =this.DateDiff(sender.config.text);
            if(diffDay===0){
                 sender.config.text  = "今天"+utils.ConvertDateToStr(sender.config.text,"hh:mm")+"更新";
            }else if(diffDay===1){
                 sender.config.text  = "昨天"+utils.ConvertDateToStr(sender.config.text,"hh:mm")+"更新";
            }else if(diffDay===2){
                sender.config.text  = "前天"+utils.ConvertDateToStr(sender.config.text,"hh:mm")+"更新";
            }else{
                sender.config.text  = utils.ConvertDateToStr(sender.config.text)+"更新";
            }
        },
        where_init: function (sender, params) {
            var from = '来自 ';
            switch (sender.config.text) {
                case 1:
                    sender.config.text = from + 'Android' + "端";
                    break;
                case 2:
                    sender.config.text = from + 'iOS' + "端";
                    break;
                case 3:
                    sender.config.text = from + 'web' + "端";
                    break;
                case 4:
                    sender.config.text = from + 'web' + "端";
                    break;
                case 0:
                    sender.config.text = from + 'web' + "端";
                    break;
            }
        },
        form_content_item_text_init: function (sender) {
            var text = sender.config.text || "";
            var reStripTagA = /<\/?a.*?>/g;
            // sender.config.text = text.replace(/\n/g, "<br/>");
            sender.config.text = (text.replace(/\n/g, "<br/>")).replace(reStripTagA, '');
            if (sender.datasource.type === "InputCheckbox") {
                sender.config.text = sender.config.text.replace(/;/g, "&nbsp ; &nbsp");
            }
        },
        form_content_item_text_didmount: function (sender, params) {
            sender.setPreText(sender.datasource.title + '： ');
        },
        range_dialog_header_close_click: function (sender) {
            this.pageview.hideDialog("range_dialog");
        },
        range_icon_click: function (sender, params) {
            this.curRowData = sender.datasource;
            this.pageview.showDialog("range_dialog");
        },
        rangetree_init: function (sender) {
            sender.config.range = this.curRowData.range;
        }

    };
    return pageLogic;
});
